package com.ask.task;

import com.ask.entity.Orders;
import com.ask.mapper.OrderMapper;
import com.ask.service.asyncService.OrderAsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executor;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderAsyncService orderAsyncService;

    @Autowired
    private Executor orderTaskExecutor;


    /**
     * 处理超时订单（超过15分钟未付款）
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟触发一次
    public void processTimeoutOrder() {
        log.info("定时处理超时订单, nowTime:{}", LocalDateTime.now());

        long start = System.currentTimeMillis();

        // select * from orders where status = #{status} and order_time &lt time;
        // 查找未付款且下单时间已超15min的订单
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(time, Orders.PENDING_PAYMENT);

        //方案1：异步跟新数据库
      ordersList.forEach(orders -> orderAsyncService.asyncProcessOrder(orders));

//        List<CompletableFuture<Void>> futures = ordersList.stream().map(order -> CompletableFuture.runAsync(() ->
//                orderAsyncService.asyncProcessOrder(order), orderTaskExecutor)).collect(Collectors.toList());

        // 等待所有异步任务完成
       // CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        //方案2： 同步跟新数据
//        ordersList.forEach(orders -> {
//            orders.setStatus(Orders.CANCELLED);
//            orders.setCancelReason("订单超时，自动取消");
//            orders.setCancelTime(LocalDateTime.now());
//            orderMapper.updateCanceledOrder(orders);
//        });

        long end = System.currentTimeMillis();
        log.info("跟新总耗时：{}", end - start);
    }

    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "* * 1 * * ?")// 每天凌晨1点出发一次
    public void processDeliveryorder() {
        log.info("定时处理一直派送中的订单，nowTime:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(time, Orders.DELIVERY_IN_PROGRESS);
        // 修改订单的状态为已完成
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
    }


}
